package app.auto.runner.base;

import static android.content.Context.INPUT_METHOD_SERVICE;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import java.util.Timer;
import java.util.TimerTask;

/***
 * 输入法工具类
 * @author Administrator
 *
 */
public class InputMethodUtil {
    public static void showInput(final Context context, final View view) {
        new Timer().schedule(new TimerTask() {

            @Override
            public void run() {

                InputMethodManager m = (InputMethodManager)

                        context.getSystemService(INPUT_METHOD_SERVICE);

                m.showSoftInput(view != null ? view : ((Activity) context).getCurrentFocus(), InputMethodManager.SHOW_FORCED);

            }

        }, 500);
    }

    public static void hideInput(final Context context, final View view) {
        new Timer().schedule(new TimerTask() {

            @Override
            public void run() {

                InputMethodManager m = (InputMethodManager)

                        context.getSystemService(INPUT_METHOD_SERVICE);

                m.hideSoftInputFromWindow(view != null ? view.getWindowToken() : ((Activity) context).getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

            }

        }, 500);
    }

    public static void hideInput(final Context context) {
        ((InputMethodManager) context.getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(((Activity) context).getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); //其次再做相应操作

    }

    public static boolean isSoftShowing(Activity ctx) {
        //获取当屏幕内容的高度
        int screenHeight = ctx.getWindow().getDecorView().getHeight();
        //获取View可见区域的bottom
        Rect rect = new Rect();
        //DecorView即为activity的顶级view
        ctx.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        //考虑到虚拟导航栏的情况（虚拟导航栏情况下：screenHeight = rect.bottom + 虚拟导航栏高度）
        //选取screenHeight*2/3进行判断
        return screenHeight * 2 / 3 > rect.bottom;
    }

    public static void toogle(final Context context, final View view) {
        new Timer().schedule(new TimerTask() {

            @Override
            public void run() {

                InputMethodManager m = (InputMethodManager)

                        context.getSystemService(INPUT_METHOD_SERVICE);

                m.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

            }

        }, 0);
    }
}
